<template>
  <template v-if="list.length>0">
    <div class="item" v-for="(ele,index) in list" :key="ele.schoolCode">
      <img class="school-logo" :src="ele.logoUrl"/>
      <div class="center">
        <div class="name">
					<div class="hot-rank" v-if="showRanking">
            <img v-if=" pageNum*10-10 +index<3" src="@/assets/images/hot.svg"/>
            <span :class="{'activeOne':(pageNum*10-10 +index)==0,'activeTwe':(pageNum*10-10 +index)==1,'activeThree':(pageNum*10-10 +index)==2}">{{ pageNum*10-10+ index + 1 }}</span>
          </div>
          <div class="sn">{{ ele.schoolName }}</div>
          <div class="major-title" v-if="ele.majorName">&nbsp;{{ele.majorName}}({{ ele.majorCode }})</div>
          <template v-if="route.path === '/ai'">
            <el-tag class="tag" v-if="ele.recommendTypeDesc === '冲'">可冲刺</el-tag>
            <el-tag class="tag" v-if="ele.recommendTypeDesc === '稳'">较稳妥</el-tag>
            <el-tag class="tag" v-if="ele.recommendTypeDesc === '保'">可保底</el-tag>
          </template>
					<el-tag v-if="ele.province" effect="light" class="tag" type="success">{{ele.province}}</el-tag>
					<el-tag v-if="ele.learningStyleName" effect="light" class="tag" type="warning">{{ele.learningStyleName}}</el-tag>
					<el-tag v-if="ele.area" effect="light" class="tag" type="danger">{{ele.area}}</el-tag>
        </div>
        <div class="major-name" v-if="route.path !=='/school'">
          <div class="collegeName"> {{ele.collegeName}}</div>
          <div class="info" v-for="item in ele.majorTags">
            <el-tag effect="light" color="#fff7e6" style="color: #d46b08;">{{item}}</el-tag>
          </div>
        </div>
        <template v-if="route.path === '/school'">
          <div class="desc" v-if="ele.schoolTags && ele.schoolTags.length>0">
            <div class="info" v-for="item in ele.schoolTags">
              <el-tag effect="light" :style="renderBg(item)">{{item}}</el-tag>
            </div>
          </div>
        </template>
        <template v-else-if="route.path !== '/school'">
          <div class="desc" v-if="ele.schoolTag && ele.schoolTag.length>0">
            <div class="info" v-for="item in ele.schoolTag">
              <el-tag effect="light" :style="renderBg(item)">{{item}}</el-tag>
            </div>
          </div>
        </template>
        <div class="desc" v-else>
          <div class="info"></div>
        </div>
      </div>
      <div class="right">
        <el-button v-if="route.path === '/school'" type="primary" color="#ff7214" plain @click="showMajor(ele)">查看专业</el-button>
        <el-button v-else type="primary" color="#ff7214" plain @click="toDetail(ele)">查看详情</el-button>
        <el-checkbox v-if="route.path !== '/school'" v-model="ele.checked" border @change="itemChecked(ele)">加入对比</el-checkbox>
      </div>
    </div>
  </template>
  <template v-else>
    <div style="min-height: 280px;display: flex;align-items: center;justify-content: center;font-size: 14px;color: #666">暂无数据，请重新选择条件查询</div>
  </template>
  <!--  院校专业对比-->
  <el-dialog
    v-model="compareDialog"
    title="院校专业对比"
    width="70%"
    destroy-on-close
    :before-close="handleClose"
    @open="getCompareData"
  >
    <div class="compare">
      <div class="header">
        <el-tag
          size="large"
          style="margin-right: 16px"
          v-for="ele in store.state.compareId"
          :key="ele.majorOutRelationId"
          closable
          @close="closeTag(ele)"
          :color="renderDialogColor()"
        >{{ele.schoolName}}({{ele.majorName}})</el-tag>
      </div>
      <div class="result">
        <el-table class="el-table" v-loading="loading" element-loading-text="数据加载中..." ref="table" :row-style="selectedRowStyle" :data="compareArr" stripe border>
          <el-table-column prop="label" width="140" align="center"></el-table-column>
          <el-table-column v-for="(column, index) in tempHeader" :key="index" align="center">
            <template #default="{ row }">
              <template v-if="row.label==='专业标签'">
                <el-tag style="margin-right:10px" type="warning" v-for="ele in row.values[index]">{{ ele }}</el-tag>
              </template>
              <template v-else>
                {{ row.values[index]? row.values[index] : '-' }}
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </el-dialog>
  <!-- 所有专业弹窗 -->
  <el-dialog class="major-dialog" v-model="majorDialog" @open="getMajor" width="60%" :before-close="closeMajorDialog">
    <div class="all-major">
      <div class="operation">
        <el-input v-model="majorName" placeholder="请输入专业名称" size="large" clearable @clear="clearMajorName"></el-input>
        <el-select v-model="studyType" placeholder="培养方式" size="large" style="width: 140px;" clearable>
          <el-option label="全日制" value="全日制"></el-option>
          <el-option label="非全日制" value="非全日制"></el-option>
        </el-select>
        <el-button @click="filterData" type="primary" color="#ff7214" size="large">搜索</el-button>
      </div>
      <div class="list" v-loading="majorLoading" element-loading-text="数据加载中...">
        <el-tabs v-if="!loading" v-model="activeTab" type="border-card" class="tabs" @tab-change="tabClick">
          <el-tab-pane :label="ele" v-for="ele in majorTypeOptions" :key="ele" :name="ele">
            <div style="height: 100%;overflow: auto">
              <el-table style="height: 100%" :data="tableData" stripe>
                <el-table-column label="学院名称" prop="collegeName"></el-table-column>
                <el-table-column label="专业名称" prop="majorName" align="center"></el-table-column>
                <el-table-column label="专业代码" prop="majorCode" width="100" align="center"></el-table-column>
                <el-table-column label="培养方式" prop="applyLearningStyleDesc" width="100" align="center"></el-table-column>
                <el-table-column label="操作" width="100" align="center">
                  <template #default="scope">
                    <el-button link type="primary" size="small" @click="toDetail(scope.row)">查看</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </el-dialog>
</template>
<script setup>
import {ref,defineProps,watch,onMounted,nextTick} from 'vue'
import {useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import {ElMessage} from 'element-plus'
import { majorCompare,majorBySchool} from '@/api/api'
import {decrypt} from '@/utils/parseDate'
const router = useRouter()
const route = useRoute()
const store= useStore()
const props = defineProps({
  data: Array,
  pageNum: Number
})
const list = ref(props.data)
const showRanking = ref(false)
// 院校专业对比loading
const loading = ref(false)
// 显示所有专业弹窗
const majorDialog = ref(false)
// 学科分了options
const majorTypeOptions = ref([])
// 培养方式
const studyType = ref('')
// 查看学校专业数据
const findSchool = ref(null)
// 专业列表
const tableData = ref([])
// 院校专业对比弹窗
const compareDialog = ref(false)
// 激活的专业
const activeTab = ref('')
// 搜索专业
const majorName = ref('')
// 所有专业
const allData = ref([])
// 加载专业loading
const majorLoading = ref(false)
// 院校专业对比标题
const header = ref([
  {
    label: '学校',
    prop: 'schoolName',
  },
  {
    label: '学院',
    prop: 'collegeName',
  },
  {
    label: '专业',
    prop: 'majorName',
  },
  {
    label: '最高分',
    prop: 'lqzgf',
  },
  {
    label: '最低分',
    prop: 'lqzdf',
  },
  {
    label: '录取人数',
    prop: 'lqzrs',
  },
  {
    label: '考试内容',
    prop: 'examContent'
  },
  {
    label: '专业标签',
    prop: 'majorTags'
  }
])
const tempHeader = ref([])
// 院校对比专业数据
const compareArr = ref([])
watch(
  ()=>props.data,
  ()=>{
    list.value = props.data
  }
)
onMounted(()=>{
	if(route.path === '/hot'){
		showRanking.value = true
	}
})
// 切换学科分类tab
function tabClick(val){
  tableData.value = allData.value.filter(ele=>ele.subjectCategory===val)
}
// 过滤专业数据
function filterData(){
  if(!majorName.value){
    ElMessage.warning('请输入专业名称 !')
    return
  }
  tableData.value = []
  majorTypeOptions.value = []
  loading.value = true
  const arr = allData.value.filter(ele=>ele.majorName.includes(majorName.value))
  if(studyType.value){
    nextTick(()=>{
      tableData.value = arr.filter(ele=>ele.applyLearningStyleDesc===studyType.value)
    })
  } else {
    nextTick(()=>{
      tableData.value = [...arr]
    })
  }
  majorTypeOptions.value = [...new Set(arr.map(ele=>ele.subjectCategory))]
  activeTab.value = majorTypeOptions.value[0]
  loading.value = false
}
// 清空专业名称输入框
function clearMajorName(){
  majorTypeOptions.value = [...new Set(allData.value.map(ele=>ele.subjectCategory))].filter(item=>item)
  activeTab.value = majorTypeOptions.value[0]
  tableData.value = allData.value.filter(ele=>ele.subjectCategory===activeTab.value)
}
// 显示所有专业弹窗
function showMajor(val){
  findSchool.value = val
  majorDialog.value = true
}
// 关闭所有专业弹窗
function closeMajorDialog(){
  majorDialog.value = false
}
// 获取所有专业
async function getMajor(){
  try{
    majorLoading.value = true
    const data = {
      schoolCode: findSchool.value.schoolCode
    }
    const res = await majorBySchool(data)
    const result = JSON.parse(decrypt(res))
    if(result.status === 0){
      majorTypeOptions.value = [...new Set(result.result.map(ele=>ele.subjectCategory))].filter(item=>item)
      activeTab.value = majorTypeOptions.value[0]
      allData.value = result.result
      tableData.value = result.result.filter(ele=>ele.subjectCategory=== activeTab.value)
    }
    majorLoading.value = false
  } catch (e) {
  }
}
// 获取对比数据
function getCompareData(){
  loading.value = true
  const compareId = store.state.compareId
  if(compareId.length === 2){
    majorCompare({
      majorOutRelationIdA: compareId[0].majorOutRelationId,
      majorOutRelationIdB: compareId[1].majorOutRelationId
    }).then(res=>{
      const result = JSON.parse(decrypt(res))
      if(result.status === 0){
        transposeTable([result.result.majorInfoA,result.result.majorInfoB])
      }
    })
  } else {
    loading.value = false
  }
}
// 跳转详情
function toDetail(val){
  // if(store.state.noChance){
  //   ElMessage({
  //     type: 'warning',
  //     message: '您今天的查询次数已达到上限，为了保障大家都能正常使用，可以明天继续查询～',
  //     offset: 100
  //   })
  //   return
  // }
	let url = ''
	if(majorDialog.value){
		url = router.resolve({path: `/school/${findSchool.value.schoolCode}/detail`,query:{majorOutRelationId:val.majorOutRelationId}}).href
	} else {
		url = router.resolve({path: `/school/${val.schoolCode}/detail`,query:{majorOutRelationId:val.majorOutRelationId}}).href
	}
  window.open(url)
}
// 加入对比
function itemChecked(val){
  const tempArr = list.value.slice()
  const arr = store.state.compareId.slice()
  const isExist = arr.some(ele=>ele===val.majorOutRelationId)
  tempArr.forEach(ele=>{
    if(ele.majorOutRelationId ===val.majorOutRelationId){
      if(ele.checked){
        arr.push(val)
        store.commit('setCompareId',arr)
      } else {
        const r = arr.filter(ele=>ele.majorOutRelationId!==val.majorOutRelationId)
        store.commit('setCompareId',r)
      }
      // ele.checked = !ele.checked
    }
  })
  list.value = tempArr
  if(arr.length >= 2  && !isExist){
    compareDialog.value = true
    return
  }
}
function renderBg(val){
  let color = ''
  let bgColor = ''
  if(val === '985'){
    color = '#871400'
    bgColor = '#fff2e8'
  } else if(val === '211'){
    color = '#d35400'
    bgColor = '#fefce0'
  } else if(val === '双一流'){
    color = '#874d00'
    bgColor = '#fffbe6'
  } else if(val === '普通高校'){
    color = '#00474f'
    bgColor = '#b5f5ec'
  } else{
    color = '#909399'
    bgColor = '#ffffff'
  }
	return {
		color: color,
		backgroundColor: bgColor,
		cursor: 'pointer'
	}
}
// 行列互换
function transposeTable(data){
  const arr = header.value.slice()
  const transposedData = arr.map(column=>({
    label: column.label,
    prop: column.prop,
    values: data.map(row => row[column.prop]),
  }))
  // 更新表格的数据和列定义
  tempHeader.value = data.map((row, index) =>{
    return ({
      label: '',
      prop: `column${index}`,
    })
  })
  compareArr.value = transposedData
  loading.value = false
  compareDialog.value = true
}
// 渲染院校专业对比背景色
function renderDialogColor(){
  const r = Math.floor(Math.random()*266)
  const g = Math.floor(Math.random()*266)
  const b = Math.floor(Math.random()*266)
  return `rgba(${r},${g},${b},0.06)`
}
// 关闭tag
function closeTag(val){
  const arr = store.state.compareId.filter(ele=>ele.majorOutRelationId!==val.majorOutRelationId)
  if(arr.length === 0){
    compareArr.value = []
    list.value = list.value.map(ele=>{
      return {
        ...ele,
        checked: false
      }
    })
    compareDialog.value = false
  }
  store.commit('setCompareId',[...arr])
}
// 关闭弹窗
function handleClose(){
  store.commit('setCompareId',[])
  compareArr.value = []
  list.value = list.value.map(ele=>{
    return {
      ...ele,
      checked: false
    }
  })
  compareDialog.value = false
}
// 第一行加粗显示
function selectedRowStyle({row,rowIndex}){
  if(rowIndex === 0){
    return {'font-weight': '700'}
  }
}
</script>
<style lang="less" scoped>
.item{
  padding-top: 21px;
  padding-bottom: 30px;
  border-bottom: 1px solid rgb(238,238,238);
  padding-left: 80px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  &:last-child{
    border-bottom: none;
  }
  .school-logo{
    position: absolute;
    left: 0;
    top: 21px;
    // background-color: aqua;
    border-radius: 50%;
    width: 60px;
    height: 60px;
  }
  .center{
    .name{
      display: flex;
      align-items: center;
      .sn{
        font-size: 18px;
        font-weight: 700;
      }
      .major-title{
        font-weight: 600;
      }
			.tag{
				margin-left: 10px;
				font-size: 12px;
			}
			.hot-rank{
				// margin-left: 12px;
				display: flex;
				align-items: center;
				transform: translateX(-10px);
				img{
					margin-top: -4px;
					margin-right: -8px;
					width: 24px;
					height: 24px;
					z-index: 99;
				}
				span{
					padding: 1px 8px;
					background-color: #ccc;
					border-radius: 4px;
					// padding: ;
					font-size: 12px;
					color: #fff;
				}
				.activeOne{
					background-color: #c0392b;
				}
				.activeTwe{
					background-color: #d35400;
				}
				.activeThree{
					background-color: #e67e22;
				}
			}
      .addr-img{
        margin: 0 10px;
        width: 25px;
        height: 25px;
      }
      .addr{
        font-size: 14px;
        color: #888;
      }
    }
    .desc{
      margin-top: 21px;
      display: flex;
      align-items: center;
      .info{
        position: relative;
        padding-right: 10px;
        font-size: 14px;
        color: #555;
        // &::after{
        //   position: relative;
        //   top: 1px;
        //   right: -10px;
        //   content: '';
        //   display: inline-block;
        //   height: 12px;
        //   padding-right: 10px;
        //   border-left: 1px solid #c5c5c5;
        // }
        // &:last-child::after{
        //   position: relative;
        //   top: 1px;
        //   right: -10px;
        //   content: '';
        //   display: inline-block;
        //   height: 0;
        //   padding-right: 10px;
        // }
      }
    }
    .result{
      display: flex;
      align-items: center;
      margin-top: 16px;
      .el{
        padding: 4px 8px;
        font-size: 14px;
        margin-right: 8px;
        color: #ff7214;
        background-color: #ff721420;
        border-radius: 4px;
      }
    }
    .major-name{
      display: flex;
      align-items: center;
      margin-top: 21px;
      font-size: 14px;
      color: #555;
      .collegeName{
        //font-weight: 400;
        color: #333;
      }
      .el-tag{
        margin-left: 10px;
      }
    }
		.learn-type{
			margin: 20px 0;
			font-size: 14px;
      color: #555;
		}
  }
  .right{
    display: flex;
    align-items: center;
    .el-checkbox{
      margin-left: 10px;
      color: #ff7214;
    }
    .el-checkbox.is-bordered.is-checked{
      color: #ff7214;
      border-color: #ff7214;
    }
    /deep/ .el-checkbox__input.is-checked+.el-checkbox__label{
      color: #ff7214 !important;
    }
    
    /deep/ .el-checkbox__input.is-checked .el-checkbox__inner{
      border-color: #ff7214;
      background-color: #ff7214;
    }
  }
}
.compare{
  box-sizing: border-box;
  .result{
    box-sizing: border-box;
    margin-top: 15px;
    height: 322px;
    overflow: auto;
    .el-table{
      height: 100%;
    }
    .el-table{
      :deep(.el-table__header-wrapper){
        display: none;
      }
    }
  }
}
.major-dialog{
  .el-dialog__header {
    display: none;
  }
  .all-major{
    .operation{
      transform: translateY(-20px);
      .el-input{
        width: 240px;
        margin-right: 10px;
      }
      .el-select{
        margin-right: 10px;
      }
      .el-button{
        color: #fff;
      }
    }
    .list{
      box-sizing: border-box;
      height: 595px;
      .tabs{
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        height: 100%;
        overflow: hidden;
        :deep(.el-tabs__content){
          flex: 1;
          .el-tab-pane{
            height: 100%;
          }
        }
      }
    }
  }
}

</style>
